// pages/myself/integral/RedeemDetails.js
var Zan = require('../../../dist/index');
var WxParse = require('../../../wxParse/wxParse.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
var eventStatus = 0; // 0=没选规格;1=加入购物车;2=立即购买

Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    product: {},
    listSpec: [],
    showDialog: false,
    count: 1,
    radioCheckVal01: 0,
    radioCheckVal02: 0,
    radioCheckVal03: 0,
    price: 0,
    selectedSpec: null,
    mobile: null,
    ipsId: '',
    intelvalue01: 0,
    intelvalue02: 0,
    intelvalue03: 0,
    item01: '',
    item02: '',
    item03: '',
    listspecid: '',
    RealListspec: {},
    canIUseMobile: wx.canIUse('button.open-type.getPhoneNumber')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    if (app.globalData.userId) {
      bind(options);
    } else {
      // 由于 openId 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userAndTenantInfoCallback = res => {
        bind(options);
      }
    }
    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo) {
      this.setData({
        mobile: app.globalData.userAndTenantInfo.mobile
      })
    }

    wx.getUserInfo({
      success: res => {
        this.setData({
          nickName: res.userInfo.nickName,
        })
      }
    })

    wx.showShareMenu({
      withShareTicket: true //要求小程序返回分享目标信息
    })

    this.setData({
      ipsId: options.ipsId
    })
    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onPullDownRefresh();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    eventStatus = 0;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    network._post_json(this, api.integralDetails, { ipsId: this.data.ipsId }, success);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.product.title,
      path: '/pages/myself/integral/RedeemDetails?shared=' + app.globalData.userAndTenantInfo.id + '&ipsId=' + this.data.product.id,
      // imageUrl: this.data.saleInfo.qrCode,
      success: function (res) {
        // 转发成功
        if (res.shareTickets) {
          wx.getShareInfo({
            shareTicket: res.shareTickets,
            success: function (res) {
              network._post_json(this, api.updateFxcs, { directShareNums: 0, directShareQunNums: 1 }, fxcsSuccess);
            },
            fail: function (res) {
              // 转发失败
              network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
            }
          })
        } else {
          network._post_json(this, api.updateFxcs, { directShareNums: 1, directShareQunNums: 0 }, fxcsSuccess);
        }

      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog
    })
    
  },

  selected: function(e){    
    var checkFlag = isSelectedOk(this);
    if (checkFlag == -2) {
      this.showZanToast('请选择规格');
    } else if (checkFlag == -1) {
      this.showZanTopTips(1, '您的积分为' + this.data.user.integral + "，不够兑换");
    } else {
      toPayPage(this);
    }
  },
 
  /**
   * 进入下一步提交订单
   */
  next: function (e) {
    var checkFlag = isSelectedOk(this);
    if (checkFlag == -2) {
      this.toggleDialog(e);
    } else if (checkFlag == -1) {
      this.showZanTopTips(1,'您的积分为' + this.data.user.integral + "，不够兑换");
    } else {
      toPayPage(this);
    }
    
  },


  /**
   * 减商品数量
   */
  reduce: function (e) {
    if (this.data.count > 1) {
      this.data.count--;
      this.setData({
        count: this.data.count
      });

      calcPoint(this);
    }
  },
  /**
   * 加商品数量
   */
  add: function (e) {
    this.data.count++;
    this.setData({
      count: this.data.count
    });

    calcPoint(this);
  },

  
  getPhoneNumber: function (e) {
    if (e.detail.encryptedData) {
      network._post_json(this, api.wxphone, { encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, bindSuccess);
    }
  },

  //选择一个规格后
  specSelect:function(e){
    var currData = e.currentTarget.dataset;
    var fatidx = currData.fatidx;
    var subidx = currData.subidx;
    var currBind = this.data.specArr[fatidx].specDetails[subidx];
    if (currBind.class != "disabled"){
      if (currBind.class){
        currBind.class = "";
      }else{
        currBind.class = "active";
      }      
      

      //处理当前选择的规格类型的其他规格
      for (var n = 0; n < this.data.specArr[fatidx].specDetails.length; n++) {
        if (this.data.specArr[fatidx].specDetails[n].class == "active" && subidx!=n){
          this.data.specArr[fatidx].specDetails[n].class = "";
        }
      }

      this.setData(this.data);
    } 

    calcPoint(this);
  }

}))
//Page结束

var toPayPage = function(that){
  //跳到支付页
  that.setData({
    showDialog: false,
  });
  try {
    wx.setStorageSync('RedeemDetailsData', that.data);
  } catch (e) {
  }
  wx.navigateTo({
    url: '/pages/pay/IntegralPay',
  })
}

// 生成小程序显示的规格数据
var buildSpecArr = function(that, res){
  var specArr = [];
  for (var i = 1; i < 4; i++) {
    if (res.data.data.ips["specType" + i]) {
      specArr[i - 1] = {
        specType: res.data.data.ips["specType" + i],
        specDetails: []
      };
    } else {
      break;
    }
  }
 
  for (var m = 0; m < res.data.data.ips.inteCombs.length;m++){
    for (var n = 0; n < specArr.length; n++){
      var isSame = false;
      var specTmp = res.data.data.ips.inteCombs[m]["specDetails" + (n + 1)];
      if (specArr[n].specDetails.length){
        for (var s = 0; s < specArr[n].specDetails.length; s++) {
          if (specArr[n].specDetails[s].name == specTmp) {
            isSame = true;
            break;
          }
        }
      }      
      if(! isSame){
        specArr[n].specDetails.push({
          name: specTmp,
          class: ""
        });
      }
    }
  }

  that.setData({
    specArr: specArr
  })

}

//计算当前积分
var calcPoint = function(that){
  //多规格
  if (that.data.product.ipType == 2) {
    //检查是否选择了全部类型的规格
    var selectedSpec=[];
    for (var m = 0; m < that.data.specArr.length; m++) {
      for (var n = 0; n < that.data.specArr[m].specDetails.length; n++) {
        if (that.data.specArr[m].specDetails[n].class == "active"){
          selectedSpec.push(that.data.specArr[m].specDetails[n].name);
          break;
        }
      }
    }
    //规格都选了
    if (selectedSpec.length == that.data.specArr.length){
      for (var m = 0; m < that.data.product.inteCombs.length; m++) {
        var isCurr = true;
        for (var n = 0; n < selectedSpec.length; n++){
          if (that.data.product.inteCombs[m]["specDetails" + (n + 1)] != selectedSpec[n]){
            isCurr = false;
            break;
          }
        }
        if(isCurr){
          var selectedSpecNames = "";
          for (var n = 0; n < selectedSpec.length; n++) {
            if(n!=0){
              selectedSpecNames += "+";
            }
            selectedSpecNames += selectedSpec;
          }
          that.setData({
            selectedSpecNames: selectedSpec,
            selectedSpecRowIdx: m,
            selectedSpecRow: that.data.product.inteCombs[m],
            currChangeIntegral: that.data.product.inteCombs[m].specValue2 * that.data.count,
            currProPrice: that.data.product.inteCombs[m].specValue1 * that.data.count / 100
          })
        }
      }
    }else{
      //没选全规格，计算积分及价格的范围
      var minChangeIntegral, minProPrice, maxChangeIntegral, maxProPrice;
      for (var m = 0; m < that.data.product.inteCombs.length; m++) {
        if(m==0){
          minChangeIntegral = that.data.product.inteCombs[m].specValue2;
          minProPrice = that.data.product.inteCombs[m].specValue1;
          maxChangeIntegral = that.data.product.inteCombs[m].specValue2;
          maxProPrice = that.data.product.inteCombs[m].specValue1;
        }else{
          if (minChangeIntegral > that.data.product.inteCombs[m].specValue2){
            minChangeIntegral = that.data.product.inteCombs[m].specValue2;
          }
          if (minProPrice > that.data.product.inteCombs[m].specValue1) {
            minProPrice = that.data.product.inteCombs[m].specValue1;
          }
          if (maxChangeIntegral < that.data.product.inteCombs[m].specValue2) {
            maxChangeIntegral = that.data.product.inteCombs[m].specValue2;
          }
          if (maxProPrice < that.data.product.inteCombs[m].specValue1) {
            maxProPrice = that.data.product.inteCombs[m].specValue1;
          }
        }
      }
      var currProPrice = 0, currChangeIntegral=0;
      if (minProPrice == maxProPrice) {
        currProPrice = minProPrice / 100;
      } else {
        currProPrice = (minProPrice / 100) + "-" + (maxProPrice / 100);
      }
      if (minChangeIntegral == maxChangeIntegral) {
        currChangeIntegral = minChangeIntegral;
      } else {
        currChangeIntegral = minChangeIntegral + "-" + maxChangeIntegral;
      }
      that.setData({
        selectedSpecNames: "",
        selectedSpecRow: null,
        currChangeIntegral: currChangeIntegral,
        currProPrice: currProPrice
      })
    }

  }else{
    //统一规格
    that.setData({
      selectedSpecNames: "",
      currChangeIntegral: that.data.product.changeIntegral * that.data.count,
      currProPrice: that.data.product.proPrice * that.data.count / 100
    })

  }
  
}

//校验当前选择的规格及数量是否可以购买
var isSelectedOk = function(that){  
  //多规格
  if (that.data.product.ipType == 2) {
    if (that.data.selectedSpecRow) {
      if (that.data.user.integral >= that.data.currChangeIntegral) {
        return 1;
      } else {
        //规格选了，但是积分不够
        return -1;
      }
    } else {
      //规格没选
      return -2;
    }
  }else{
    if (that.data.user.integral >= that.data.currChangeIntegral) {
      return 1;
    } else {
      //规格选了，但是积分不够
      return -1;
    }
  }
  
}

// 获取商品列表结果
var success = function (that, res) {  
  if (res.data.data.ips.ipType == 2){
    buildSpecArr(that, res);
  }else{

  }

  if (res.data.data) {
    that.setData({
      product: res.data.data.ips,
      user: res.data.data.user
    })
 
    WxParse.wxParse('details', 'html', res.data.data.ips.ipDetails, that, 0);    
    
    calcPoint(that);
  }
}

var addSuccess = function (that, res) {
  // that.setData({
  //   count: 1,
  //   radioCheckVal: 0,
  //   selectedSpec: that.data.listSpec[0]
  // })
  allPrice(that, that.data.product);
  that.showZanToast('添加成功');
}

var addShoppingCart = function (that) {
  if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
    if (that.data.product.listSpec && that.data.product.listSpec.length > 0) {
      if (that.data.selectedSpec) {
        // 这里是把商品加入购物车的代码
        network._post_json(that, api.addShoppingCart, { product: { ipsId: that.data.product.id, specId: that.data.selectedSpec.id, count: that.data.count } }, addSuccess);
      }
    } else {
      // 没有规格的商品
      network._post_json(that, api.addShoppingCart, { product: { ipsId: that.data.product.id, count: that.data.count } }, addSuccess);
    }
  } else {
    that.showZanTopTips('商品已下架');
  }
}

var startPay = function (that) {
  if (that.data.product.isVirtual == 0 && that.data.product.isActive == 1) {
    var product = {};
    var products = [];
    product.id = that.data.product.id;
    product.title = that.data.product.title;
    product.smallImgUrl = that.data.product.smallImgUrl;
    product.count = that.data.count;
    // 这里是开始购买车的代码
    if (that.data.product.inteCombs && that.data.product.inteCombs.length > 0) {
      if (that.data.selectedSpec && that.data.listspecid) {
        product.price = that.data.RealListspec.specValue1;
        product.specId = that.data.product.inteCombs[that.data.listspecid].id;
        product.specName = that.data.selectedSpec;
      } else if (that.data.selectedSpec && !that.data.listspecid) {
        product.price = that.data.product.price;
        product.specId = that.data.product.inteCombs[0].id;
        product.specName = that.data.selectedSpec;
      }
    } else {
      // 没有规格的商品
      product.price = that.data.product.price;
    }
    products.push(product);
    try {
      wx.setStorageSync('products', products)
    } catch (e) {
    }

    allPrice(that, that.data.product, that.data.listspecid);
    wx.navigateTo({
      url: '/pages/pay/Pay'
    })
  } else {
    that.showZanTopTips('商品已下架');
  }
}

var bindSuccess = function (that, res) {
  app.globalData.userAndTenantInfo.mobile = res.data.data.mobile;
  that.setData({
    mobile: res.data.data.mobile
  })
}

var fxcsSuccess = function (that, res) {
  that.showZanToast('分享成功');
}

var bind = function (options) {
  if (options.shared) {
    wx.request({
      url: api.bindUserFormQRcode,
      data: {
        openId: app.globalData.openId,
        userId: app.globalData.userId,
        tenantId: app.globalData.tenantId,
        distributorId: options.shared,
        ipsId: options.ipsId
      },
      method: 'POST',
      success: function (res) {
      }
    });
  }
}